<!--新增 流程-->
<template>
  <el-dialog
    v-toggle-full
    class="base-dialog material-basic-info-dialog"
    :class="{ readonly: readOnly }"
    :title="title"
    :visible.sync="dialogVisible"
    destroy-on-close
    :append-to-body="true"
    :custom-class="'panna-dialog_big'"
    :before-close="handleClose"
    @closed="closedDialog"
  >
    <p slot="title">{{ title }}</p>

    <h3>{{ dataList.WorkFlowNodeInformation }}</h3>
    <el-form
      ref="formData"
      v-loading="formLoading"
      class="base-pipeline-layout"
      :rules="formRules"
      :model="formData"
      label-width="100px"
    >
      <el-form-item :label="dataList.WorkFlowName" prop="flowName">
        <el-select
          v-model="formData.flowName"
          value-key="formData.flowName"
          :disabled="readOnly"
          :placeholder="btn.PleaseSelect"
        >
          <!-- <el-option label="材料入库流程" value="材料入库流程" />
                    <el-option label="材料出库流程" value="材料出库流程" />
                    <el-option label="台账流程" value="台账流程" />
                    <el-option label="化验单流程" value="化验单流程" />
          <el-option label="合格证流程" value="合格证流程" />-->
          <el-option
            v-for="(item, index) in workFlowTypeList"
            :key="index"
            :label="item.name"
            :value="item.dictCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="dataList.WorkFlowType" prop="flowType">
        <el-select
          v-model="formData.flowType"
          value-key="formData.flowType"
          :disabled="readOnly"
          :placeholder="btn.PleaseSelect"
          filterable
        >
          <!-- <el-option label="上级审批" value="1" /> -->
          <el-option :label="dataList.SpecifyUserGroupApproval" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item
        :label="dataList.SupportWithdrawalOrNot"
        prop="isAllowWithdraw"
        label-width="100"
        style="margin-left: 25px"
      >
        <el-select
          v-model="formData.isAllowWithdraw"
          value-key="formData.isAllowWithdraw"
          :disabled="readOnly"
          :placeholder="btn.PleaseSelect"
          filterable
          style="width: 100px"
        >
          <el-option :label="dataList.No" value="0" />
          <el-option :label="dataList.Yes" value="1" />
        </el-select>
      </el-form-item>
    </el-form>
    <h3>{{ dataList.WorkFlowNodeInformation }}</h3>
    <template v-if="!readOnly"></template>
    <template>
      <el-button
        type="primary"
        icon="el-icon-plus"
        :disabled="readOnly"
        size="mini"
        @click="addmembers"
        >{{ btn.Add }}</el-button
      >
      <el-table :data="tableData" :border="true">
        <el-table-column prop="flowNodeName" :label="dataList.NodeName">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.flowNodeName"
              autocomplete="off"
              size="small"
              :placeholder="dataList.EnterNodeName"
              :disabled="readOnly"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="flowCurrentNode" label="节点顺序">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.flowCurrentNode"
              autocomplete="off"
              size="small"
              :disabled="true"
              :placeholder="dataList.EnterNodeOrder"
              type="number"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="flowNodeGroup" :label="dataList.UserGroup">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.flowNodeGroup"
              :disabled="readOnly"
              :placeholder="dataList.SelectUserGroup"
            >
              <el-option
                v-for="(item, index) in groupList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="remark" :label="dataList.Remark">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark"
              autocomplete="off"
              size="small"
              :disabled="readOnly"
              :placeholder="dataList.EnterRemark"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column v-if="readOnly == false && editId == ''" :label="btn.operate">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="danger"
              :disabled="readOnly"
              plain
              @click="delmembers(scope.$index, scope.row)"
              >{{ btn.Delete }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </template>
    <span v-if="!readOnly" slot="footer" class="base-dialog-footer">
      <el-button
        v-loading="submitLoad"
        :disabled="submitLoad"
        type="primary"
        @click="submitForm"
        >{{ btn.Save }}</el-button
      >
      <el-button @click="handleClose">{{ btn.Cancel }}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  GetWorkFlowMainInfo,
  CreateWorkFlowMain,
  UpdateWorkFlowMain,
  GetWorkFlowDetailList,
} from "../../api/WorkFlow/WorkFlow.js";
import { GetUserGroupList } from "../../api/Permission/PermissionUserGroup.js";
import { getDictList } from "../../api/System/SystemDict.js";
export default {
  name: "WorkFlowDialog",
  props: {
    value: {
      type: Boolean,
      default: false,
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
    editId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      title: "",
      dialogVisible: false,
      submitLoad: false,
      groupList: [],
      workFlowTypeList: [],
      tableData: [],
      filterForm: {
        flowName: "",
      },
      formData: {
        flowName: "",
        flowType: "",
        workFlowNode: [],
        isAllowWithdraw: "0",
      },
      formRules: {
        flowName: [{ required: true, message: this.$t("ModuleWorkFlow.WorkFlow.EnterWorkFlowName") }],
        flowType: [{ required: true, message: this.$t("ModuleWorkFlow.WorkFlow.SelectWorkFlowType") }],
      },
      formLoading: false,
    };
  },
  computed: {
    btn() {
      return this.$t("ModuleWorkFlow.buttons");
    },
    dataList() {
      return this.$t("ModuleWorkFlow.WorkFlow");
    },
  },
  watch: {
    value: function() {
      this.dialogVisible = this.value;
      if (this.value) {
        this.init();
      }
    },
  },
  created() {

  },
  beforeDestroy() {
    // 开发热更新后，同步外面的数据
    this.handleClose();
  },

  methods: {
    // 初始化
    async init() {
      // 获取材料列表 每次打开获取 防止数据不是最新
      this.formLoading = true;
      GetUserGroupList({ pageIndex: 1, pageSize: 999 }).then((res) => {
        this.groupList = res.data.dataList;
      });
      getDictList({ dictCode: "WorkFlow", value: "1" }).then((res) => {
        this.workFlowTypeList = res.data;
      });
      // editId 存在表示编辑 不存在表示新增
      this.title = this.readOnly
        ? this.$t("ModuleWorkFlow.buttons.Look")
        : this.editId
          ? this.$t("ModuleWorkFlow.buttons.Edit")
          : this.$t("ModuleWorkFlow.buttons.Add");

      // 编辑材料 先获取材料信息
      if (this.editId) {
        // 获取材料信息
        GetWorkFlowMainInfo({ id: this.editId })
          .then((res) => {
            debugger
            this.formLoading = false;
            this.formData = res.data;
            this.formData.isAllowWithdraw = this.formData.isAllowWithdraw == null ? "" : this.formData.isAllowWithdraw.toString();
            this.formData.flowType = this.formData.flowType.toString();
            this.tableData = this.transformData(res.data.workFlowNode);
          })
          .catch(() => {
            this.formLoading = false;
          });
      } else {
        this.formLoading = false;
      }
    },
    addmembers() {
      var count = this.tableData.length;
      this.tableData.push({
        flowNnodeName: "",
        flowCurrentNode: count + 1,
        flowNodeRole: "",
        remark: "",
      });
    },
    delmembers(index, row) {
      var that = this;
      this.$confirm(this.$t("ModuleWorkFlow.buttons.IsDeleteFlow"), this.$t("ModuleWorkFlow.buttons.Tips"), {
        confirmButtonText: this.$t("ModuleWorkFlow.buttons.Delete"),
        cancelButtonText: this.$t("ModuleWorkFlow.buttons.Cancel"),
        type: "warning",
      })
        .then(() => {
          if (row.nodeId) {
            GetWorkFlowDetailList({ id: row.nodeId })
              .then((res) => {
                that.tableData.splice(index, 1);
              })
              .finally(() => {
                // instance.confirmButtonLoading = false;
                // done();
              });
          } else {
            that.tableData.splice(index, 1);
          }
        })
        .catch(() => {
          // 点取消的提示
          return;
        });
    },
    // 转换数据 data => Array
    transformData(workFlowNode) {
      return workFlowNode.map((item) => {
        return {
          id: item.id,
          flowNodeName: item.flowNodeName,
          flowCurrentNode: item.flowCurrentNode,
          flowNodeGroup: item.flowNodeGroup,
          remark: item.remark,
        };
      });
    },
    // 提交表单
    submitForm() {
      // 校验表单必填项
      this.$refs.formData.validate((valid) => {
        if (valid) {
          var result = true;
          var msg = [];
          // 当前编辑ID是否存在 存在则去更新流程配置信息
          const requestData = JSON.parse(JSON.stringify(this.formData));
          const tableData = JSON.parse(JSON.stringify(this.tableData));
          this.tableData.forEach((item, index) => {
            const no = index + 1;
            if (item.flowNnodeName === "") {
              result = result && false;
              var LineNodeFront = this.$t('ModuleWorkFlow.WorkFlow.LineNodeFront')
              var LineNodeAfter = this.$t('ModuleWorkFlow.WorkFlow.LineNodeAfter')
              msg.push(LineNodeFront + no + LineNodeAfter);
            }
            if (item.flowNodeRole === "") {
              result = result && false;
              var LineUserFront = this.$t('ModuleWorkFlow.WorkFlow.LineUserFront')
              var LineUserAfter = this.$t('ModuleWorkFlow.WorkFlow.LineUserAfter')
              msg.push(LineUserFront + no + LineUserAfter);
            }
            if (!result) {
              var temp = "";
              msg.forEach((v) => {
                temp += `<li>${v}</li>`;
              });
              return this.$notify({
                title: this.$t('ModuleWorkFlow.WorkFlow.ProcessNodeInformation'),
                dangerouslyUseHTMLString: true,
                type: "warning",
                duration: 3000,
                message: `<ul>${temp}</ul>`,
              });
            }
          });
          requestData.workFlowNode = tableData.map((item) => {
            return {
              id: item.id == null ? 0 : item.id,
              flowNodeName: item.flowNodeName,
              flowCurrentNode: item.flowCurrentNode,
              flowNodeGroup: item.flowNodeGroup,
              remark: item.remark,
            };
          });
          this.submitLoad = true;
          if (this.editId) {
            this.editAPI(requestData);
          } else {
            // 新增
            this.addAPI(requestData);
          }
        } else {
          this.$message.error(this.$t("ModuleWorkFlow.buttons.PleaseComplete"));
        }
      });
    },
    // 新增接口
    addAPI(data) {
      CreateWorkFlowMain(data)
        .then((res) => {
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = false;
        });
    },
    // 编辑接口
    editAPI(data) {
      UpdateWorkFlowMain({
        ...data,
        id: this.editId,
      })
        .then((res) => {
          this.SuccessfulOperation();
        })
        .catch(() => {
          this.submitLoad = false;
        });
    },
    // 操作成功回调用
    SuccessfulOperation() {
      this.submitLoad = false;
      this.$emit("success");
      this.handleClose();
    },
    // 关闭弹框
    handleClose() {
      this.tableData = [];
      //   !不可用赋值方式，监听不到响应式
      //   this.formData = {
      //     FlowName: "",
      //     FlowType: "",
      //     workFlowNode: [],
      //   };
      this.closedDialog();
      this.$emit("input", false);
    },
    // 关闭弹框动画结束
    closedDialog() {
      // 动画结束后在清空表单 防止页面闪烁
    },
  },
};
</script>

<style lang="scss" scoped>
h3 {
  color: #02a7f0;
  margin-bottom: 10px;
}
.add-line {
  width: 100%;
  margin-top: 10px;
  border: 1px dashed #dcdfe6;
}
.material-icon {
  font-size: 22px;
  margin-right: 10px;
  cursor: pointer;
}
.material-basic-info-dialog ::v-deep .el-card {
  margin-bottom: 20px;
}
.box-card {
  .clearfix:before,
  .clearfix:after {
    content: none;
  }
  .clearfix {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .card-header-right {
      img {
        vertical-align: middle;
        width: 150px;
        height: 50px;
        margin-right: 20px;
      }
      i {
        cursor: pointer;
      }
    }
  }
}
</style>
